<template>
  <div class="user-container">
    <div class="user-header">
      <div class="user-avatar">
        <img 
          :src="userInfo?.img || defaultAvatar" 
          alt="用户头像" 
          @error="handleImageError"
        />
        <div class="avatar-edit" @click="triggerFileUpload">
          <el-icon><CameraFilled /></el-icon>
          <input 
            type="file" 
            ref="fileInput" 
            style="display: none" 
            accept="image/*"
            @change="handleFileChange"
          />
        </div>
      </div>
      <div class="user-info">
        <h2 class="username">{{ userInfo?.username || '用户名' }}</h2>
        <p class="user-id">ID: {{ userInfo?.id || '未知' }}</p>
      </div>
      <div class="auth-buttons" v-if="!userInfo">
        <button class="login-btn" @click="$router.push('/login')">
          <el-icon><SignIn /></el-icon>
          登录
        </button>
        <button class="register-btn" @click="$router.push('/register')">
          <el-icon><Plus /></el-icon>
          注册
        </button>
      </div>
      <div class="auth-buttons" v-else>
        <button class="logout-btn" @click="handleLogout">
          <el-icon><SwitchButton /></el-icon>
          退出登录
        </button>
      </div>
    </div>

    <div class="user-content">
      <div class="user-sidebar">
        <div class="menu-item active">
          <el-icon><User /></el-icon>
          <span>个人信息</span>
        </div>
        <router-link to="/orders" class="menu-item">
          <el-icon><List /></el-icon>
          <span>我的订单</span>
        </router-link>
        <router-link to="/favorites" class="menu-item">
          <el-icon><StarFilled /></el-icon>
          <span>我的收藏</span>
        </router-link>
        <router-link to="/address" class="menu-item">
          <el-icon><LocationFilled /></el-icon>
          <span>收货地址</span>
        </router-link>
        <router-link to="/seckill-orders" class="menu-item">
          <el-icon><Timer /></el-icon>
          <span>秒杀订单</span>
        </router-link>
        <router-link :to="`/customer-service/${userInfo?.username}`" class="menu-item">
          <el-icon><Service /></el-icon>
          <span>在线客服</span>
        </router-link>
      </div>

      <div class="user-main">
        <div class="info-card">
          <h3 class="card-title">基本信息</h3>
          <div class="info-form">
            <div class="form-item">
              <label>用户名</label>
              <input type="text" v-model="formData.username" placeholder="请输入用户名" />
            </div>
            <div class="form-item">
              <label>手机号</label>
              <input type="tel" v-model="formData.phone" placeholder="请输入手机号" />
            </div>
            <div class="form-item">
              <label>性别</label>
              <div class="gender-options">
                <label class="gender-option">
                  <input type="radio" v-model="formData.gender" :value="1" />
                  <span>男</span>
                </label>
                <label class="gender-option">
                  <input type="radio" v-model="formData.gender" :value="2" />
                  <span>女</span>
                </label>
              </div>
            </div>
            <div class="form-item">
              <label>密码</label>
              <div class="password-input">
                <input :type="showPassword ? 'text' : 'password'" v-model="formData.password" placeholder="请输入密码" />
                <button class="toggle-password" @click="showPassword = !showPassword">
                  <el-icon>
                    <View v-if="showPassword" />
                    <Hide v-else />
                  </el-icon>
                </button>
              </div>
            </div>
          </div>
          <div class="card-footer">
            <button class="save-btn" @click="handleSave">保存修改</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import axios from '@/axios/index'
import defaultAvatar from '../../assets/images/avatar.png'
import { User, List, LocationFilled, CameraFilled, Plus, StarFilled, SwitchButton, View, Hide, Service, Timer } from '@element-plus/icons-vue'
import { ElMessage, ElLoading } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const userInfo = ref(null)
const loading = ref(false)
const showPassword = ref(false)

const formData = reactive({
  id: undefined,
  username: '',
  phone: '',
  gender: 1,
  password: '',
  img: ''
})

const fileInput = ref(null)

const handleLogout = async () => {
  try {
    const res = await axios.post('/user/logout')
    if (res.code === 1) {
      // 清除用户状态
      userStore.clearUserInfo()
      // 清除axios默认请求头中的token
      delete axios.defaults.headers.common['authorization']
      
      ElMessage.success('退出登录成功')
      // 跳转到登录页
      router.push('/login')
    } else {
      ElMessage.error(res.msg || '退出登录失败')
    }
  } catch (error) {
    console.error('退出登录失败:', error)
    ElMessage.error('退出登录失败，请稍后重试')
  }
}

const handleSave = async () => {
  try {
    // 表单验证
    if (!formData.username || !formData.phone) {
      ElMessage.warning('请填写完整信息')
      return
    }
    
    // 手机号格式验证
    if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
      ElMessage.warning('请输入正确的手机号')
      return
    }

    const res = await axios.post('/user/update', formData)
    if (res.code === 1) {
      ElMessage.success('修改成功')
      // 重新获取用户信息
      await fetchUserInfo()
    } else {
      ElMessage.error(res.msg || '修改失败')
    }
  } catch (error) {
    console.error('修改个人信息失败:', error)
    ElMessage.error('修改失败，请稍后重试')
  }
}

const fetchUserInfo = async () => {
  try {
    const res = await axios.get('/user/info')
    console.log('获取到的用户信息:', res.data)
    if (res.code === 1 && res.data) {
      userInfo.value = res.data
      // 更新表单数据
      Object.assign(formData, {
        id: res.data.id,
        username: res.data.username,
        phone: res.data.phone,
        gender: res.data.gender || 1,
        img: res.data.img
      })
      console.log('更新后的userInfo:', userInfo.value)
    } else {
      // token失效等异常，跳转登录
      router.push('/login')
    }
  } catch (e) {
    router.push('/login')
  }
}

const triggerFileUpload = () => {
  // 触发文件上传
  fileInput.value.click()
}

// 处理文件上传
const handleFileChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请上传图片文件')
    return
  }
  
  // 验证文件大小（限制为2MB）
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过2MB')
    return
  }

  const loading = ElLoading.service({
    lock: true,
    text: '上传中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    // 创建 FormData
    const formData = new FormData()
    formData.append('file', file)

    // 调用上传接口
    const res = await axios.post('/user/upload/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (res.code === 1) {
      console.log('上传成功，图片URL:', res.data)
      ElMessage.success('头像更新成功')
      // 更新用户信息
      await fetchUserInfo()
    } else {
      ElMessage.error(res.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传头像失败:', error)
    ElMessage.error('上传失败，请稍后重试')
  } finally {
    loading.close()
    // 清空文件输入框，允许重复上传同一文件
    event.target.value = ''
  }
}

const handleImageError = (e) => {
  console.error('头像加载失败:', e)
  e.target.src = defaultAvatar // 加载失败时使用默认头像
}

onMounted(async () => {
  await fetchUserInfo()
})
</script>

<style scoped>
.user-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.user-header {
  background: white;
  border-radius: 12px;
  padding: 30px;
  display: flex;
  align-items: center;
  gap: 30px;
  margin-bottom: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.user-avatar {
  position: relative;
  width: 120px;
  height: 120px;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #f8f9fa;
}

.avatar-edit {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 36px;
  height: 36px;
  background: #4CAF50;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  transition: background 0.3s;
}

.avatar-edit:hover {
  background: #45a049;
}

.user-info {
  flex: 1;
}

.username {
  font-size: 24px;
  color: #2c3e50;
  margin: 0 0 10px 0;
}

.user-id {
  color: #666;
  margin: 0;
}

.user-content {
  display: grid;
  grid-template-columns: 250px 1fr;
  gap: 30px;
}

.user-sidebar {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 15px;
  color: #666;
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.3s;
}

.menu-item:hover {
  background: #f8f9fa;
  color: #4CAF50;
}

.menu-item.active {
  background: #4CAF50;
  color: white;
}

.menu-item i {
  width: 20px;
  text-align: center;
}

.user-main {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.card-title {
  font-size: 20px;
  color: #2c3e50;
  margin: 0 0 30px 0;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.info-form {
  display: grid;
  gap: 20px;
}

.form-item {
  display: grid;
  grid-template-columns: 100px 1fr;
  align-items: center;
  gap: 20px;
}

.form-item label {
  color: #666;
}

.form-item input {
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.3s;
  width: 100%;
  box-sizing: border-box;
}

.form-item input:focus {
  border-color: #4CAF50;
  outline: none;
}

.form-item input:disabled {
  background: #f8f9fa;
  cursor: not-allowed;
}

.card-footer {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
  text-align: right;
}

.save-btn {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  transition: background 0.3s;
}

.save-btn:hover {
  background: #45a049;
}

.auth-buttons {
  display: flex;
  gap: 15px;
  margin-left: auto;
}

.login-btn, .register-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
}

.login-btn {
  background: #4CAF50;
  color: white;
}

.login-btn:hover {
  background: #45a049;
  transform: translateY(-2px);
}

.register-btn {
  background: #f8f9fa;
  color: #2c3e50;
  border: 2px solid #e9ecef;
}

.register-btn:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.login-btn i, .register-btn i {
  font-size: 16px;
}

.logout-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
  background: #f56c6c;
  color: white;
}

.logout-btn:hover {
  background: #e64242;
  transform: translateY(-2px);
}

@media (max-width: 768px) {
  .user-content {
    grid-template-columns: 1fr;
  }
  
  .user-header {
    flex-direction: column;
    text-align: center;
  }
  
  .auth-buttons {
    margin: 20px 0 0 0;
    justify-content: center;
  }
  
  .form-item {
    grid-template-columns: 1fr;
    gap: 8px;
  }
}

.gender-options {
  display: flex;
  gap: 20px;
}

.gender-option {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
}

.gender-option input[type="radio"] {
  width: 16px;
  height: 16px;
  margin: 0;
}

.password-input {
  position: relative;
  display: flex;
  align-items: center;
}

.toggle-password {
  position: absolute;
  right: 10px;
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  padding: 5px;
  display: flex;
  align-items: center;
}

.toggle-password:hover {
  color: #4CAF50;
}

.form-item input[type="password"] {
  padding-right: 40px;
}
</style> 